package com.guo.mixframe.framework.receivers.rpc

import com.guo.mixframe.framework.exception.CoreException
import com.guo.mixframe.framework.exceptions.CustomException
import com.guo.mixframe.framework.log.LogPrint
import com.guo.mixframe.framework.urls.URLMapping
import com.guo.mixframe.messages.BaseRequestWrapper
import io.vertx.core.AbstractVerticle
import io.vertx.core.MultiMap
import io.vertx.core.eventbus.Message
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * @author  gx
 * @description
 */
open class BaseDispatcher : AbstractVerticle() {
  var urls:Set<String>? = null
  var urlType = 0

  override fun start() {
    urls?.forEach {url -> {
      vertx.eventBus().consumer<ByteArray>(url){
        message ->
        GlobalScope.launch { processMessage(message) }
      }
    }}
  }

  private fun processMessage(message: Message<ByteArray>) {
    val headers = message.headers()
    val url = headers.get("url")
    val request = createRequestWrapper(url,headers,message)
    if(request == null){
      LogPrint.logger.error("createRequestWrapper fail,$url")
      message.fail(-1,"Unknown")
      return
    }
    if(!URLMapping.isUrlValid(url)){
      LogPrint.logger.error("invalid url:$url")
      sendErrorToBus(request,CoreException.invalidUrl)
      return
    }

  }

  private fun sendErrorToBus(request: BaseRequestWrapper, error: Int) {
      request.sendError(CustomException(error))
  }

  private fun createRequestWrapper(url: String?, headers: MultiMap, message: Message<ByteArray>): BaseRequestWrapper? {
      return null
  }

}
